using System;
using System.Web.Security;
using System.Globalization;

using System.Collections.Specialized;
using System.Configuration.Provider;

namespace Caramel.NHibernate.Membership
{
	internal static class SecurityConfigUtil
	{
		public static MembershipPasswordFormat GetPasswordFormat(NameValueCollection config, MembershipPasswordFormat defaultValue)
		{
			if (config["passwordFormat"] != null)
			{
				switch (config["passwordFormat"])
				{
					case "Clear":
						return MembershipPasswordFormat.Clear;
					case "Encrypted":
						return MembershipPasswordFormat.Encrypted;
					case "Hashed":
						return MembershipPasswordFormat.Hashed;
					default:
						throw new ProviderException("Password format specified is invalid.");
				}
			}

			return defaultValue;
		}

		public static bool GetBoolValue(NameValueCollection config, string valueName, bool defaultValue)
		{
			if (config[valueName] == null)
			{
				return defaultValue;
			}

			bool value;

			if (!Boolean.TryParse(config[valueName], out value))
			{
				throw new ProviderException(String.Format("The value must be a boolean '{0}'.", valueName));
			}

			return value;
		}

		public static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed)
		{
			if (config[valueName] == null)
			{
				return defaultValue;
			}

			int value;

			if (!Int32.TryParse(config[valueName], out value))
			{
				if (zeroAllowed)
				{
					throw new ProviderException(String.Format("The value must be a non-negative 32-bit integer for property '{0}'.", valueName));
				}

				throw new ProviderException(String.Format("The value must be a positive 32-bit integer for property '{0}'.", valueName));
			}

			if (zeroAllowed && (value < 0))
			{
				throw new ProviderException(String.Format("The value must be a non-negative 32-bit integer for property '{0}'.", valueName));
			}

			if (!zeroAllowed && (value <= 0))
			{
				throw new ProviderException(String.Format("The value must be a positive 32-bit integer for property '{0}'.", valueName));
			}

			if ((maxValueAllowed > 0) && (value > maxValueAllowed))
			{
				throw new ProviderException(String.Format("The value '{0}' can not be greater than '{1}'.", valueName, maxValueAllowed.ToString(CultureInfo.InvariantCulture)));
			}

			return value;
		}
	}
}
